﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Aliphant.Mvvm.XEvent.Events;
using Aliphant.Mvvm.XEvent.Events.Base.SubScription;

using CuteWallpaperDemo.Models;

using DataModel.Contants;

namespace CuteWallpaperDemo.UI
{
    /// <summary>
    /// MainPictureList.xaml 的交互逻辑
    /// </summary>
    public partial class MainPictureList : UserControl
    {
        private ProjectAgent _projectAgent;
        private WindowEvent _windowEvent;

        private double MIN_ITEM_SIZE = 180;
        private double MAX_ITEM_SIZE = 220;

        SubScriptionToken? _subscriptionToken1;

        public MainPictureList()
        {
            InitializeComponent();

            _projectAgent = ProjectContainer.ProjectAgent;
            _windowEvent = _projectAgent.EventManager.GetEvent<WindowEvent>();

            RegistSubScriptionToken();
        }

        private void RegistSubScriptionToken()
        {
            _subscriptionToken1 = _windowEvent.Subscribe(UpdateLayout, (p) => p.EventId == EventIds.UpdateLayout);
        }

        private void UnRegistSubScriptionToken()
        {
            _windowEvent.UnSubscribe(_subscriptionToken1);
        }

        private void UpdateLayout(WindowEvent @event)
        {
            ListenLayout();
        }


        private void ListenLayout()
        {
            // 获取 ItemsControl 的实际宽度
            double containerWidth = mainList.ActualWidth;

            // 计算列数和 Item 宽度
            int mincolCount = (int)(containerWidth / MAX_ITEM_SIZE);    //最小列数
            int maxcolCount = (int)(containerWidth / MIN_ITEM_SIZE);    //最大列数

            int columnCount = Math.Max(mincolCount, maxcolCount);
            if (columnCount < 2) columnCount = 2;
            int rowCount = (int)Math.Ceiling((double)mainList.Items.Count / (double)columnCount);
            if (rowCount < 1) rowCount = 1;

            double itemWidth = containerWidth / columnCount;

            var uniformGrid = FindVisualChild<UniformGrid>(mainList, "uniformGrid");

            if (uniformGrid != null)
            {
                uniformGrid.Columns = columnCount;
                double itemHeight = (itemWidth / 3) * 2;
                foreach (var item in mainList.Items)
                {
                    if (mainList.ItemContainerGenerator.ContainerFromItem(item) is FrameworkElement container)
                    {
                        container.Width = itemWidth;
                        container.Height = itemHeight;
                    }
                }
            }
        }

        private T? FindVisualChild<T>(DependencyObject parent, string name) where T : FrameworkElement
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is T && ((T)child).Name == name)
                {
                    return (T)child;
                }

                var result = FindVisualChild<T>(child, name);
                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ListenLayout();
        }

        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ListenLayout();
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            UnRegistSubScriptionToken();
        }
    }
}
